<template>
  <div class="logs-container">
    <div class="page-header">
      <h2>操作日志</h2>
      <p class="page-description">查看系统操作记录和审计日志</p>
    </div>

    <!-- 搜索过滤器 -->
    <el-card class="filter-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="操作人员">
          <el-input 
            v-model="searchForm.operator"
            placeholder="请输入操作人员"
            clearable
            style="width: 200px;"
          />
        </el-form-item>
        
        <el-form-item label="操作类型">
          <el-select 
            v-model="searchForm.type"
            placeholder="请选择操作类型"
            clearable
            style="width: 150px;"
          >
            <el-option label="登录" value="login" />
            <el-option label="登出" value="logout" />
            <el-option label="查重" value="check" />
            <el-option label="上传" value="upload" />
            <el-option label="删除" value="delete" />
            <el-option label="导出" value="export" />
            <el-option label="设置" value="settings" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            :shortcuts="dateShortcuts"
          />
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleSearch" :loading="searching">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><RefreshRight /></el-icon>
            重置
          </el-button>
          <el-button type="success" @click="handleExport">
            <el-icon><Download /></el-icon>
            导出日志
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 日志列表 -->
    <el-card class="table-card">
      <el-table 
        :data="logList" 
        v-loading="loading"
        stripe
        @sort-change="handleSortChange"
      >
        <el-table-column prop="id" label="ID" width="80" />
        
        <el-table-column prop="operator" label="操作人员" width="120">
          <template #default="{ row }">
            <div class="user-info">
              <el-avatar :size="24" :src="row.avatar">
                <el-icon><User /></el-icon>
              </el-avatar>
              <span>{{ row.operator }}</span>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="type" label="操作类型" width="100">
          <template #default="{ row }">
            <el-tag :type="getTypeTagType(row.type)">
              {{ getTypeText(row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="description" label="操作描述" min-width="200" />
        
        <el-table-column prop="ip" label="IP地址" width="140" />
        
        <el-table-column prop="userAgent" label="浏览器" width="150">
          <template #default="{ row }">
            <el-tooltip :content="row.userAgent" placement="top">
              <span class="user-agent">{{ getBrowserInfo(row.userAgent) }}</span>
            </el-tooltip>
          </template>
        </el-table-column>
        
        <el-table-column prop="status" label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="row.status === 'success' ? 'success' : 'danger'" size="small">
              {{ row.status === 'success' ? '成功' : '失败' }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column 
          prop="createTime" 
          label="操作时间" 
          width="180"
          sortable="custom"
        />
        
        <el-table-column label="操作" width="100" fixed="right">
          <template #default="{ row }">
            <el-button 
              type="text" 
              size="small" 
              @click="handleViewDetail(row)"
            >
              详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 详情对话框 -->
    <el-dialog v-model="detailVisible" title="操作详情" width="600px">
      <div v-if="currentLog" class="log-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="操作ID">
            {{ currentLog.id }}
          </el-descriptions-item>
          <el-descriptions-item label="操作人员">
            {{ currentLog.operator }}
          </el-descriptions-item>
          <el-descriptions-item label="操作类型">
            <el-tag :type="getTypeTagType(currentLog.type)">
              {{ getTypeText(currentLog.type) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="currentLog.status === 'success' ? 'success' : 'danger'">
              {{ currentLog.status === 'success' ? '成功' : '失败' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="IP地址" :span="2">
            {{ currentLog.ip }}
          </el-descriptions-item>
          <el-descriptions-item label="操作时间" :span="2">
            {{ currentLog.createTime }}
          </el-descriptions-item>
          <el-descriptions-item label="操作描述" :span="2">
            {{ currentLog.description }}
          </el-descriptions-item>
          <el-descriptions-item label="浏览器信息" :span="2">
            {{ currentLog.userAgent }}
          </el-descriptions-item>
        </el-descriptions>
        
        <div v-if="currentLog.details" class="log-details">
          <h4>详细信息</h4>
          <pre>{{ JSON.stringify(currentLog.details, null, 2) }}</pre>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { 
  Search, 
  RefreshRight, 
  Download, 
  User 
} from '@element-plus/icons-vue'

// 搜索表单
const searchForm = ref({
  operator: '',
  type: '',
  dateRange: null
})

// 分页信息
const pagination = ref({
  page: 1,
  size: 20,
  total: 0
})

// 状态
const loading = ref(false)
const searching = ref(false)
const detailVisible = ref(false)

// 数据
const logList = ref([])
const currentLog = ref(null)

// 时间快捷选项
const dateShortcuts = [
  {
    text: '今天',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setHours(0, 0, 0, 0)
      return [start, end]
    }
  },
  {
    text: '昨天',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24)
      start.setHours(0, 0, 0, 0)
      end.setHours(0, 0, 0, 0)
      return [start, end]
    }
  },
  {
    text: '最近7天',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    }
  },
  {
    text: '最近30天',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      return [start, end]
    }
  }
]

// 模拟日志数据
const mockLogs = [
  {
    id: 1,
    operator: '张老师',
    type: 'login',
    description: '用户登录系统',
    ip: '192.168.1.100',
    userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
    status: 'success',
    createTime: '2024-03-20 09:15:30',
    avatar: null,
    details: { loginMethod: 'password', device: 'PC' }
  },
  {
    id: 2,
    operator: '李老师',
    type: 'check',
    description: '执行论文查重检测',
    ip: '192.168.1.101',
    userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
    status: 'success',
    createTime: '2024-03-20 10:30:45',
    avatar: null,
    details: { fileName: '毕业论文.docx', similarity: 25.6 }
  },
  {
    id: 3,
    operator: '王老师',
    type: 'export',
    description: '导出学生管理数据',
    ip: '192.168.1.102',
    userAgent: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36',
    status: 'success',
    createTime: '2024-03-20 14:20:15',
    avatar: null,
    details: { exportType: 'excel', recordCount: 150 }
  },
  {
    id: 4,
    operator: '赵老师',
    type: 'settings',
    description: '修改系统设置',
    ip: '192.168.1.103',
    userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
    status: 'success',
    createTime: '2024-03-20 16:45:20',
    avatar: null,
    details: { changedSettings: ['maxFileSize', 'similarityThreshold'] }
  },
  {
    id: 5,
    operator: '孙老师',
    type: 'delete',
    description: '删除学生提交记录',
    ip: '192.168.1.104',
    userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
    status: 'failed',
    createTime: '2024-03-20 17:30:10',
    avatar: null,
    details: { reason: '权限不足', targetId: 'submission_123' }
  }
]

// 获取操作类型对应的标签类型
const getTypeTagType = (type) => {
  const typeMap = {
    login: 'success',
    logout: 'info',
    check: 'primary',
    upload: 'warning',
    delete: 'danger',
    export: 'success',
    settings: 'warning'
  }
  return typeMap[type] || 'info'
}

// 获取操作类型文本
const getTypeText = (type) => {
  const typeMap = {
    login: '登录',
    logout: '登出',
    check: '查重',
    upload: '上传',
    delete: '删除',
    export: '导出',
    settings: '设置'
  }
  return typeMap[type] || type
}

// 获取浏览器信息
const getBrowserInfo = (userAgent) => {
  if (userAgent.includes('Chrome')) return 'Chrome'
  if (userAgent.includes('Firefox')) return 'Firefox'
  if (userAgent.includes('Safari')) return 'Safari'
  if (userAgent.includes('Edge')) return 'Edge'
  return '未知'
}

// 加载日志列表
const loadLogs = async () => {
  try {
    loading.value = true
    
    console.log('加载操作日志:', {
      page: pagination.value.page,
      size: pagination.value.size,
      search: searchForm.value
    })
    
    // 模拟API请求
    await new Promise(resolve => setTimeout(resolve, 800))
    
    // 模拟过滤
    let filteredLogs = [...mockLogs]
    
    if (searchForm.value.operator) {
      filteredLogs = filteredLogs.filter(log => 
        log.operator.includes(searchForm.value.operator)
      )
    }
    
    if (searchForm.value.type) {
      filteredLogs = filteredLogs.filter(log => 
        log.type === searchForm.value.type
      )
    }
    
    // 模拟分页
    const start = (pagination.value.page - 1) * pagination.value.size
    const end = start + pagination.value.size
    
    logList.value = filteredLogs.slice(start, end)
    pagination.value.total = filteredLogs.length
    
  } catch (error) {
    console.error('加载日志失败:', error)
    ElMessage.error('加载日志失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = async () => {
  searching.value = true
  pagination.value.page = 1
  await loadLogs()
  searching.value = false
}

// 重置
const handleReset = () => {
  searchForm.value = {
    operator: '',
    type: '',
    dateRange: null
  }
  pagination.value.page = 1
  loadLogs()
}

// 导出日志
const handleExport = () => {
  console.log('导出操作日志')
  ElMessage.success('日志导出功能开发中...')
}

// 查看详情
const handleViewDetail = (row) => {
  currentLog.value = row
  detailVisible.value = true
}

// 排序变化
const handleSortChange = (sort) => {
  console.log('排序变化:', sort)
  loadLogs()
}

// 分页大小变化
const handleSizeChange = (size) => {
  pagination.value.size = size
  pagination.value.page = 1
  loadLogs()
}

// 当前页变化
const handleCurrentChange = (page) => {
  pagination.value.page = page
  loadLogs()
}

// 页面加载时获取数据
onMounted(() => {
  console.log('操作日志页面已加载')
  loadLogs()
})
</script>

<style scoped>
.logs-container {
  padding: 24px;
}

.page-header {
  margin-bottom: 24px;
}

.page-header h2 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 24px;
  font-weight: 600;
}

.page-description {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.filter-card {
  margin-bottom: 16px;
}

.table-card {
  margin-bottom: 24px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.user-agent {
  font-size: 13px;
  color: #606266;
}

.pagination-container {
  margin-top: 20px;
  text-align: center;
}

.log-detail {
  max-height: 60vh;
  overflow-y: auto;
}

.log-details {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

.log-details h4 {
  margin: 0 0 12px 0;
  color: #303133;
  font-size: 14px;
  font-weight: 600;
}

.log-details pre {
  background: #f8f9fa;
  padding: 12px;
  border-radius: 4px;
  font-size: 12px;
  color: #606266;
  white-space: pre-wrap;
  word-break: break-all;
}

:deep(.el-table) {
  font-size: 13px;
}

:deep(.el-form--inline .el-form-item) {
  margin-right: 16px;
  margin-bottom: 16px;
}
</style>